#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#include "proto.h"


int main(void)
{
    struct sockaddr_in readaddr;
    struct msg_st snd_data;
    char recv_buffer[BUFSIZE] = {0};
    ssize_t sent_bytes, recv_bytes;
    int udp_socket = socket(AF_INET, SOCK_DGRAM, 0); // udp socket
    struct sockaddr_in server_addr;
    socklen_t server_addr_len;

    if (-1 == udp_socket) {
        perror("socket()");
        return 1;
    }

    // 发送数据
    snd_data.id = 102;
    strncpy(snd_data.name, "/tmp/test.txt", NAMESIZE);

    readaddr.sin_family = AF_INET;
    inet_aton(RCVADDR, &readaddr.sin_addr); // 
    readaddr.sin_port = htons(PORT);

    // 发送数据
    sent_bytes = sendto(udp_socket, &snd_data, sizeof(snd_data.id) + strlen(snd_data.name) + 1,\
            0, (struct sockaddr *)&readaddr, sizeof(readaddr));

    if (-1 == sent_bytes) {
        perror("sendto()");
        close(udp_socket);
        return 1;
    }

    printf("发送 %zd B 数据到 %s:%d\n", sent_bytes, RCVADDR, PORT);


    // 接收服务器响应
    server_addr_len = sizeof(server_addr);
    recv_bytes = recvfrom(udp_socket, recv_buffer, BUFSIZE - 1, 0,\
            (struct sockaddr *)&server_addr, &server_addr_len);

    if (-1 == recv_bytes) {
        perror("recvfrom()");
        close(udp_socket);
        return 1;
    }

    // 确保接收到的数据以 null 结尾
    recv_buffer[recv_bytes] = '\0';

    // 打印服务器响应
    printf("从 %s:%d 接收 %zd B数据\n", inet_ntoa(server_addr.sin_addr), \
            ntohs(server_addr.sin_port), recv_bytes);
    printf("数据: %s\n", recv_buffer);

    close(udp_socket);

    return 0;
}
